package com.rightsidetech.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.dto.response.AdminHomeTopResp;
import com.rightsidetech.commom.dto.response.AgentHomeTopResp;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.SysUpdateStatusReq;
import com.rightsidetech.system.dtos.request.UpdateImageReq;
import com.rightsidetech.system.dtos.request.UpdatePhoneNoReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentInfoAddReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentInfoReq;
import com.rightsidetech.system.dtos.request.agent.SysAgentInfoUpdateReq;
import com.rightsidetech.system.dtos.response.SysRoleSelectResp;
import com.rightsidetech.system.dtos.response.agent.AgentAppInfoResp;
import com.rightsidetech.system.dtos.response.agent.SysAgentInfoResp;
import com.rightsidetech.system.dtos.response.agent.SysDropDownNameResp;
import com.rightsidetech.system.entity.*;
import com.rightsidetech.system.mapper.*;
import com.rightsidetech.system.service.SysAgentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.Date;
import java.util.List;

/**
 * @Author: yhr
 * @Date: 2021-10-25 15:04
 */
@Slf4j
@Service("sysAgentInfoServiceImpl")
public class SysAgentInfoServiceImpl implements SysAgentInfoService {
    @Resource
    private SysAgentLoginInfoMapper sysAgentLoginInfoMapper;
    @Resource
    private SysAgentRoleMapper sysAgentRoleMapper;
    @Resource
    private SysAgentInfoMapper sysAgentInfoMapper;
    @Resource
    private SysAgentRoleAccountMapper sysAgentRoleAccountMapper;
    @Resource
    private SysUserLoginInfoMapper sysUserLoginInfoMapper;
    @Resource
    private SysAgentLoginHistoryMapper sysAgentLoginHistoryMapper;
    @Resource
    private SysStoreInfoMapper sysStoreInfoMapper;
    @Resource
    private SysStoreAccountInfoMapper sysStoreAccountInfoMapper;

    @Override
    public ResponseData<PageInfo<SysAgentInfoResp>> page(SysAgentInfoReq req,Long loginInfoId) {
        SysUserLoginInfo loginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<SysAgentInfoResp> page = sysAgentLoginInfoMapper.page(req,loginInfo.getSysCompanyAreaId());
        return ResponseData.success(new PageInfo<>(page));
    }

    @Override
    public ResponseData saveAgentInfo(SysAgentInfoAddReq req, Long loginInfoId) throws Exception {
        List<Long> longList = sysAgentLoginInfoMapper.selectNameMobile(req.getLoginName(), req.getMobileNo());
        if (!ObjectUtils.isEmpty(longList) || longList.size() > 0){
            return ResponseData.fail("帐号或手机号已存在");
        }
        int countRole = sysAgentRoleMapper.selectAgentById(req.getRoleId());
        if (countRole < 1) {
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }
        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(req.getAgentInfoId());
        if (ObjectUtils.isEmpty(sysAgentInfo)){
            return ResponseData.fail(CodeIdEnum.NOAGENT);
        }
        SysAgentLoginInfo agentLoginInfo = new SysAgentLoginInfo();
        agentLoginInfo.setLoginName(req.getLoginName());
        agentLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
        agentLoginInfo.setPassword(DigestUtils.md5DigestAsHex((req.getPassword() + agentLoginInfo.getSalt()).getBytes()));
        agentLoginInfo.setAgentInfoId(req.getAgentInfoId());
        agentLoginInfo.setUserName(req.getUserName());
        agentLoginInfo.setMobileNo(req.getMobileNo());
        agentLoginInfo.setIsAgent((byte) 1);
        String loginName = sysUserLoginInfoMapper.selectLoginName(loginInfoId);
        if (StringUtils.isEmpty(loginName)){
            return ResponseData.fail("未找到创建者");
        }
        agentLoginInfo.setCreaterName(loginName);
        agentLoginInfo.setCreatedAt(new Date());
        sysAgentLoginInfoMapper.insertSelective(agentLoginInfo);

        SysAgentRoleAccount account = new SysAgentRoleAccount();
        account.setLoginInfoId(agentLoginInfo.getId());
        account.setRoleId(req.getRoleId());
        account.setCreatedAt(new Date());
        sysAgentRoleAccountMapper.insertSelective(account);

        this.createRole(req.getAgentInfoId(),req.getAgentInfoId());

        return ResponseData.success();
    }
    private void createRole(Long agentId,Long loginId) throws Exception {
        List<SysRoleSelectResp> sysRoleSelectResps = sysAgentRoleMapper.selectChooseList(agentId);
        boolean delivery = true;
        for (SysRoleSelectResp resp:sysRoleSelectResps) {
            if ("送货员".equals(resp.getName())){
                delivery = false;
                continue;
            }
        }
        if (delivery){
            SysAgentRole role1 = new SysAgentRole();
            role1.setName("送货员");
            role1.setRoleDetail("默认创建送货员角色");
            role1.setAgentInfoId(agentId);
            role1.setCreatedAt(new Date());
            role1.setCreaterId(loginId);
            sysAgentRoleMapper.insertSelective(role1);
        }
    }

    @Override
    public ResponseData updateAgentInfo(SysAgentInfoUpdateReq req, Long loginInfoId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail("帐号不存在");
        }
        int countRole = sysAgentRoleMapper.selectAgentById(req.getRoleId());
        if (countRole < 1) {
            return ResponseData.fail(CodeIdEnum.NOROLE);
        }
        List<Long> longList = sysAgentLoginInfoMapper.selectNameMobile(req.getLoginName(), req.getMobileNo());
        for (Long id:longList) {
            if (!id.equals(req.getId())){
                return ResponseData.fail("帐号或手机号已存在");
            }
        }
        SysAgentLoginInfo agentLoginInfo = new SysAgentLoginInfo();
        agentLoginInfo.setId(req.getId());
        agentLoginInfo.setLoginName(req.getLoginName());
        if (!StringUtils.isEmpty(req.getPassword())){
            agentLoginInfo.setSalt(String.valueOf(Math.random() * 900000 + 100000));
            agentLoginInfo.setPassword(DigestUtils.md5DigestAsHex((req.getPassword() + agentLoginInfo.getSalt()).getBytes()));
        }
        //agentLoginInfo.setAgentInfoId(req.getAgentInfoId());
        agentLoginInfo.setUserName(req.getUserName());
        agentLoginInfo.setMobileNo(req.getMobileNo());
        sysAgentLoginInfoMapper.updateByPrimaryKeySelective(agentLoginInfo);
//        SysAgentInfo sysAgentInfo = sysAgentInfoMapper.selectByPrimaryKey(req.getAgentInfoId());
//        if (ObjectUtils.isEmpty(sysAgentInfo)){
//            return ResponseData.fail("代理商不存在");
//        }
        SysAgentRoleAccount agentRoleAccount = sysAgentRoleAccountMapper.selectByLoginId(req.getId());
        if (!ObjectUtils.isEmpty(agentRoleAccount)){
            SysAgentRole sysAgentRole = sysAgentRoleMapper.selectByPrimaryKey(agentRoleAccount.getRoleId());
            if (ObjectUtils.isEmpty(sysAgentRole)){
                return ResponseData.fail("未找到关联角色");
            }
            agentRoleAccount.setRoleId(req.getRoleId());
            agentRoleAccount.setUpdatedAt(new Date());
            sysAgentRoleAccountMapper.updateByPrimaryKeySelective(agentRoleAccount);
        }else {
            SysAgentRoleAccount roleAccount = new SysAgentRoleAccount();
            roleAccount.setRoleId(req.getRoleId());
            roleAccount.setCreatedAt(new Date());
            roleAccount.setLoginInfoId(loginInfo.getId());
            sysAgentRoleAccountMapper.insertSelective(roleAccount);
        }
        return ResponseData.success();
    }

    @Override
    public ResponseData delAgentInfo(DelReq req) {
        SysAgentLoginInfo info = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(info) || info.getIsDeleted() == 1){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        sysAgentLoginInfoMapper.updateStatus(req.getId(), (byte) 1, info.getStatus());
        sysAgentRoleAccountMapper.deleteByLoginId(req.getId());
        return ResponseData.success();
    }

    @Override
    public ResponseData updateAgentInfoStatus(SysUpdateStatusReq req) {
        SysAgentLoginInfo info = sysAgentLoginInfoMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtils.isEmpty(info)){
            return ResponseData.fail(CodeIdEnum.NOACCOUNT);
        }
        if (info.getStatus().equals(req.getStatus())){
            return ResponseData.fail(CodeIdEnum.REPEATSTATUS);
        }
        sysAgentLoginInfoMapper.updateStatus(req.getId(), info.getIsDeleted(), req.getStatus());
        return ResponseData.success();
    }

    @Override
    public ResponseData<List<SysDropDownNameResp>> selectList(Long loginInfoId) {
        SysUserLoginInfo loginInfo = sysUserLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (ObjectUtils.isEmpty(loginInfo)){
            return ResponseData.fail(CodeIdEnum.NOLOGINACCOUNT);
        }
        return ResponseData.success(sysAgentLoginInfoMapper.selectList(loginInfo.getSysCompanyAreaId()));
    }

    @Override
    public Long sysUsercheckToken(String token) {
        SysAgentLoginHistory sysAgentLoginHistory = sysAgentLoginHistoryMapper.selectToken(token);
        if (StringUtils.isEmpty(sysAgentLoginHistory)){
            return null;
        }
        if (!StringUtils.isEmpty(sysAgentLoginHistory.getLogoutTime())){
            return null;
        }else if (new Date().after (sysAgentLoginHistory.getEffectiveTime())){
            return null;
        }
        return sysAgentLoginHistory.getLoginInfoId();
    }

    @Override
    public Long findAgentInfoIdByToken(String token) {
        SysAgentLoginHistory loginHistory = sysAgentLoginHistoryMapper.selectToken(token);
        if (StringUtils.isEmpty(loginHistory)){
            log.info("未找到该用户");
            return null;
        }
        SysAgentLoginInfo loginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginHistory.getLoginInfoId());
        if (StringUtils.isEmpty(loginInfo)){
            log.info("未找到该用户");
            return null;
        }
        SysAgentLoginHistory sysAgentLoginHistory = sysAgentLoginHistoryMapper.selectMaxIdByLoginInfoId(loginHistory.getLoginInfoId());
        if (StringUtils.isEmpty(sysAgentLoginHistory)){
            log.info("未找到该用户");
            return null;
        }
        if (!StringUtils.isEmpty(sysAgentLoginHistory.getLogoutTime())){
            log.info("该账户已登出");
            return null;
        }else if (new Date().after (sysAgentLoginHistory.getEffectiveTime())){
            log.info("该账户有效时间过期");
            return null;
        }
        return loginInfo.getAgentInfoId();
    }

    @Override
    public Long findAgentInfoId(Long loginInfoId) {
        SysAgentLoginInfo sysAgentLoginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
        if (!ObjectUtils.isEmpty(sysAgentLoginInfo)){
            return sysAgentLoginInfo.getAgentInfoId();
        }
        return null;
    }

    @Override
    public ResponseData<AgentAppInfoResp> agentInfo(Long loginInfoId) {
        return ResponseData.success(sysAgentLoginInfoMapper.selectAgentInfo(loginInfoId));
    }

    @Override
    public ResponseData updateHeadImg(UpdateImageReq req,Long loginId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAgentLoginInfo sysAgentLoginInfo = sysAgentLoginInfoMapper.selectByPrimaryKey(loginId);
        if (ObjectUtils.isEmpty(sysAgentLoginInfo)){
            return new ResponseData<>(CodeIdEnum.NOACCOUNT.getValue(), validate.getMessage());
        }
        if (sysAgentLoginInfo.getIsAgent() != 1){
            return ResponseData.fail("无法修改代理商头像");
        }

        sysAgentInfoMapper.updateHeadImg(req,sysAgentLoginInfo.getAgentInfoId());
        return ResponseData.success();
    }

    @Override
    public ResponseData updatePhone(UpdatePhoneNoReq req, Long loginId) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        sysAgentLoginInfoMapper.updatePhoneNo(req, loginId);
        return ResponseData.success();
    }

    @Override
    public SysAgentLoginInfo selectInfoById(Long loginId) {
        return sysAgentLoginInfoMapper.selectByPrimaryKey(loginId);
    }

    @Override
    public AdminHomeTopResp sysUserStatis(Long areaId) {
        //代理商
        Long agentNum = sysAgentInfoMapper.findAgentNumByAreaId(areaId);

        //门店
        Long storeNum = sysStoreInfoMapper.findStoreNumByAreaId(areaId);

        AdminHomeTopResp adminHomeTopResp = new AdminHomeTopResp();
        adminHomeTopResp.setTotalAgent(agentNum);
        adminHomeTopResp.setTotalStore(storeNum);
        return adminHomeTopResp;
    }

    @Override
    public SysAgentInfo selectSysAgentInfo(Long agentId) {
        return sysAgentInfoMapper.selectByPrimaryKey(agentId);
    }

    @Override
    public AgentHomeTopResp sysStoreStatisByAgentId(Long agentInfoId) {

        Long storeNum = sysStoreInfoMapper.findStoreNumByAgentId(agentInfoId);
        Long wranNum =  sysStoreAccountInfoMapper.findWarnNumByAgentId(agentInfoId);

        AgentHomeTopResp topResp = new AgentHomeTopResp();
        topResp.setTotalStore(storeNum);
        topResp.setWarnStore(wranNum);
        return topResp;
    }

    @Override
    public SysAgentLoginHistory selectHistory(Long agentLoginId) {
        //查询app的最新登录记录
        return sysAgentLoginHistoryMapper.selectAppLoginByLoginInfoId(agentLoginId);
    }

    @Override
    public List<Long> selectAllAgnetId() {
        return sysAgentInfoMapper.selectAgentIdAll();
    }

    @Override
    public SysAgentInfo findAgentInfoById(Long agentId) {
        return sysAgentInfoMapper.selectByPrimaryKey(agentId);
    }

    @Override
    public int countStatus(Long agentInfoId) {
        return sysAgentInfoMapper.countByAgentInfoId(agentInfoId);
    }

    @Override
    public List<Long> findAgentIdsByAreaIds(List<Long> agentIds) {
        return sysAgentInfoMapper.findAgentIdsByAreaIds(agentIds);
    }

    @Override
    public SysAgentLoginInfo selectByLoginInfo(Long loginInfoId) {
        return sysAgentLoginInfoMapper.selectByPrimaryKey(loginInfoId);
    }

    @Override
    public SysAgentInfoResp selectById(Long id) {
        return sysAgentLoginInfoMapper.selectById(id);
    }
}
